home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / grep16.zip / DFA.H < prev    next >
C/C++ Source or Header  |  1992-05-04  |  18KB  |  451 lines

  1. /* dfa.h - declarations for GNU deterministic regexp compiler
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written June, 1988 by Mike Haertel */
  19.  
  20. #ifdef STDC_HEADERS
  21.  
  22. #include <stddef.h>
  23. #include <stdlib.h>
  24.  
  25. #else /* !STDC_HEADERS */
  26.  
  27. #define const
  28. #include <sys/types.h>        /* For size_t.  */
  29. extern char *calloc(), *malloc(), *realloc();
  30. extern void free();
  31.  
  32. #ifndef NULL
  33. #define NULL 0
  34. #endif
  35.  
  36. #endif /* ! STDC_HEADERS */
  37.  
  38. #include <ctype.h>
  39. #ifndef isascii
  40. #define ISALNUM(c) isalnum(c)
  41. #define ISALPHA(c) isalpha(c)
  42. #define ISUPPER(c) isupper(c)
  43. #define ISLOWER(c) islower(c)
  44. #else
  45. #define ISALNUM(c) (isascii(c) && isalnum(c))
  46. #define ISALPHA(c) (isascii(c) && isalpha(c))
  47. #define ISUPPER(c) (isascii(c) && isupper(c))
  48. #define ISLOWER(c) (isascii(c) && islower(c))
  49. #endif
  50.  
  51. /* 1 means plain parentheses serve as grouping, and backslash
  52.      parentheses are needed for literal searching.
  53.    0 means backslash-parentheses are grouping, and plain parentheses
  54.      are for literal searching.  */
  55. #define RE_NO_BK_PARENS 1
  56.  
  57. /* 1 means plain | serves as the "or"-operator, and \| is a literal.
  58.    0 means \| serves as the "or"-operator, and | is a literal.  */
  59. #define RE_NO_BK_VBAR 2
  60.  
  61. /* 0 means plain + or ? serves as an operator, and \+, \? are literals.
  62.    1 means \+, \? are operators and plain +, ? are literals.  */
  63. #define RE_BK_PLUS_QM 4
  64.  
  65. /* 1 means | binds tighter than ^ or $.
  66.    0 means the contrary.  */
  67. #define RE_TIGHT_VBAR 8
  68.  
  69. /* 1 means treat \n as an _OR operator
  70.    0 means treat it as a normal character */
  71. #define RE_NEWLINE_OR 16
  72.  
  73. /* 0 means that a special characters (such as *, ^, and $) always have
  74.      their special meaning regardless of the surrounding context.
  75.    1 means that special characters may act as normal characters in some
  76.      contexts.  Specifically, this applies to:
  77.     ^ - only special at the beginning, or after ( or |
  78.     $ - only special at the end, or before ) or |
  79.     *, +, ? - only special when not after the beginning, (, or | */
  80. #define RE_CONTEXT_INDEP_OPS 32
  81.  
  82. /* Now define combinations of bits for the standard possibilities.  */
  83. #define RE_SYNTAX_AWK (RE_NO_BK_PARENS | RE_NO_BK_VBAR | RE_CONTEXT_INDEP_OPS)
  84. #define RE_SYNTAX_EGREP (RE_SYNTAX_AWK | RE_NEWLINE_OR)
  85. #define RE_SYNTAX_GREP (RE_BK_PLUS_QM | RE_NEWLINE_OR)
  86. #define RE_SYNTAX_EMACS 0
  87.  
  88. /* Number of bits in an unsigned char. */
  89. #define CHARBITS 8
  90.  
  91. /* First integer value that is greater than any character code. */
  92. #define _NOTCHAR (1 << CHARBITS)
  93.  
  94. /* INTBITS need not be exact, just a lower bound. */
  95. #define INTBITS (CHARBITS * sizeof (int))
  96.  
  97. /* Number of ints required to hold a bit for every character. */
  98. #define _CHARSET_INTS ((_NOTCHAR + INTBITS - 1) / INTBITS)
  99.  
  100. /* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
  101. typedef int _charset[_CHARSET_INTS];
  102.  
  103. /* The regexp is parsed into an array of tokens in postfix form.  Some tokens
  104.    are operators and others are terminal symbols.  Most (but not all) of these
  105.    codes are returned by the lexical analyzer. */
  106. #if __STDC__
  107.  
  108. typedef enum
  109. {
  110.   _END = -1,            /* _END is a terminal symbol that matches the
  111.                    end of input; any value of _END or less in
  112.                    the parse tree is such a symbol.  Accepting
  113.                    states of the DFA are those that would have
  114.                    a transition on _END. */
  115.  
  116.   /* Ordinary character values are terminal symbols that match themselves. */
  117.  
  118.   _EMPTY = _NOTCHAR,        /* _EMPTY is a terminal symbol that matches
  119.                    the empty string. */
  120.  
  121.   _BACKREF,            /* _BACKREF is generated by \<digit>; it
  122.                    it not completely handled.  If the scanner
  123.                    detects a transition on backref, it returns
  124.                    a kind of "semi-success" indicating that
  125.                    the match will have to be verified with
  126.                    a backtracking matcher. */
  127.  
  128.   _BEGLINE,            /* _BEGLINE is a terminal symbol that matches
  129.                    the empty string if it is at the beginning
  130.                    of a line. */
  131.  
  132.   _ALLBEGLINE,            /* _ALLBEGLINE is a terminal symbol that
  133.                    matches the empty string if it is at the
  134.                    beginning of a line; _ALLBEGLINE applies
  135.                    to the entire regexp and can only occur
  136.                    as the first token thereof.  _ALLBEGLINE
  137.                    never appears in the parse tree; a _BEGLINE
  138.                    is prepended with _CAT to the entire
  139.                    regexp instead. */
  140.  
  141.   _ENDLINE,            /* _ENDLINE is a terminal symbol that matches
  142.                    the empty string if it is at the end of
  143.                    a line. */
  144.  
  145.   _ALLENDLINE,            /* _ALLENDLINE is to _ENDLINE as _ALLBEGLINE
  146.                    is to _BEGLINE. */
  147.  
  148.   _BEGWORD,            /* _BEGWORD is a terminal symbol that matches
  149.                    the empty string if it is at the beginning
  150.                    of a word. */
  151.  
  152.   _ENDWORD,            /* _ENDWORD is a terminal symbol that matches
  153.                    the empty string if it is at the end of
  154.                    a word. */
  155.  
  156.   _LIMWORD,            /* _LIMWORD is a terminal symbol that matches
  157.                    the empty string if it is at the beginning
  158.                    or the end of a word. */
  159.  
  160.   _NOTLIMWORD,            /* _NOTLIMWORD is a terminal symbol that
  161.                    matches the empty string if it is not at
  162.                    the beginning or end of a word. */
  163.  
  164.   _QMARK,            /* _QMARK is an operator of one argument that
  165.                    matches zero or one occurences of its
  166.                    argument. */
  167.  
  168.   _STAR,            /* _STAR is an operator of one argument that
  169.                    matches the Kleene closure (zero or more
  170.                    occurrences) of its argument. */
  171.  
  172.   _PLUS,            /* _PLUS is an operator of one argument that
  173.                    matches the positive closure (one or more
  174.                    occurrences) of its argument. */
  175.  
  176.   _CAT,                /* _CAT is an operator of two arguments that
  177.                    matches the concatenation of its
  178.                    arguments.  _CAT is never returned by the
  179.                    lexical analyzer. */
  180.  
  181.   _OR,                /* _OR is an operator of two arguments that
  182.                    matches either of its arguments. */
  183.  
  184.   _LPAREN,            /* _LPAREN never appears in the parse tree,
  185.                    it is only a lexeme. */
  186.  
  187.   _RPAREN,            /* _RPAREN never appears in the parse tree. */
  188.  
  189.   _SET                /* _SET and (and any value greater) is a
  190.                    terminal symbol that matches any of a
  191.                    class of characters. */
  192. } _token;
  193.  
  194. #else /* ! __STDC__ */
  195.  
  196. typedef short _token;
  197.  
  198. #define _END -1
  199. #define _EMPTY _NOTCHAR
  200. #define _BACKREF (_EMPTY + 1)
  201. #define _BEGLINE (_EMPTY + 2)
  202. #define _ALLBEGLINE (_EMPTY + 3)
  203. #define _ENDLINE (_EMPTY + 4)
  204. #define _ALLENDLINE (_EMPTY + 5)
  205. #define _BEGWORD (_EMPTY + 6)
  206. #define _ENDWORD (_EMPTY + 7)
  207. #define _LIMWORD (_EMPTY + 8)
  208. #define _NOTLIMWORD (_EMPTY + 9)
  209. #define _QMARK (_EMPTY + 10)
  210. #define _STAR (_EMPTY + 11)
  211. #define _PLUS (_EMPTY + 12)
  212. #define _CAT (_EMPTY + 13)
  213. #define _OR (_EMPTY + 14)
  214. #define _LPAREN (_EMPTY + 15)
  215. #define _RPAREN (_EMPTY + 16)
  216. #define _SET (_EMPTY + 17)
  217.  
  218. #endif /* ! __STDC__ */
  219.  
  220. /* Sets are stored in an array in the compiled regexp; the index of the
  221.    array corresponding to a given set token is given by _SET_INDEX(t). */
  222. #define _SET_INDEX(t) ((t) - _SET)
  223.  
  224. /* Sometimes characters can only be matched depending on the surrounding
  225.    context.  Such context decisions depend on what the previous character
  226.    was, and the value of the current (lookahead) character.  Context
  227.    dependent constraints are encoded as 8 bit integers.  Each bit that
  228.    is set indicates that the constraint succeeds in the corresponding
  229.    context.
  230.  
  231.    bit 7 - previous and current are newlines
  232.    bit 6 - previous was newline, current isn't
  233.    bit 5 - previous wasn't newline, current is
  234.    bit 4 - neither previous nor current is a newline
  235.    bit 3 - previous and current are word-constituents
  236.    bit 2 - previous was word-constituent, current isn't
  237.    bit 1 - previous wasn't word-constituent, current is
  238.    bit 0 - neither previous nor current is word-constituent
  239.  
  240.    Word-constituent characters are those that satisfy isalnum().
  241.  
  242.    The macro _SUCCEEDS_IN_CONTEXT determines whether a a given constraint
  243.    succeeds in a particular context.  Prevn is true if the previous character
  244.    was a newline, currn is true if the lookahead character is a newline.
  245.    Prevl and currl similarly depend upon whether the previous and current
  246.    characters are word-constituent letters. */
  247. #define _MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn) \
  248.   ((constraint) & 1 << ((prevn) ? 2 : 0) + ((currn) ? 1 : 0) + 4)
  249. #define _MATCHES_LETTER_CONTEXT(constraint, prevl, currl) \
  250.   ((constraint) & 1 << ((prevl) ? 2 : 0) + ((currl) ? 1 : 0))
  251. #define _SUCCEEDS_IN_CONTEXT(constraint, prevn, currn, prevl, currl) \
  252.   (_MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn)             \
  253.    && _MATCHES_LETTER_CONTEXT(constraint, prevl, currl))
  254.  
  255. /* The following macros give information about what a constraint depends on. */
  256. #define _PREV_NEWLINE_DEPENDENT(constraint) \
  257.   (((constraint) & 0xc0) >> 2 != ((constraint) & 0x30))
  258. #define _PREV_LETTER_DEPENDENT(constraint) \
  259.   (((constraint) & 0x0c) >> 2 != ((constraint) & 0x03))
  260.  
  261. /* Tokens that match the empty string subject to some constraint actually
  262.    work by applying that constraint to determine what may follow them,
  263.    taking into account what has gone before.  The following values are
  264.    the constraints corresponding to the special tokens previously defined. */
  265. #define _NO_CONSTRAINT 0xff
  266. #define _BEGLINE_CONSTRAINT 0xcf
  267. #define _ENDLINE_CONSTRAINT 0xaf
  268. #define _BEGWORD_CONSTRAINT 0xf2
  269. #define _ENDWORD_CONSTRAINT 0xf4
  270. #define _LIMWORD_CONSTRAINT 0xf6
  271. #define _NOTLIMWORD_CONSTRAINT 0xf9
  272.  
  273. /* States of the recognizer correspond to sets of positions in the parse
  274.    tree, together with the constraints under which they may be matched.
  275.    So a position is encoded as an index into the parse tree together with
  276.    a constraint. */
  277. typedef struct
  278. {
  279.   unsigned index;        /* Index into the parse array. */
  280.   unsigned constraint;        /* Constraint for matching this position. */
  281. } _position;
  282.  
  283. /* Sets of positions are stored as arrays. */
  284. typedef struct
  285. {
  286.   _position *elems;        /* Elements of this position set. */
  287.   int nelem;            /* Number of elements in this set. */
  288. } _position_set;
  289.  
  290. /* A state of the regexp consists of a set of positions, some flags,
  291.    and the token value of the lowest-numbered position of the state that
  292.    contains an _END token. */
  293. typedef struct
  294. {
  295.   int hash;            /* Hash of the positions of this state. */
  296.   _position_set elems;        /* Positions this state could match. */
  297.   char newline;            /* True if previous state matched newline. */
  298.   char letter;            /* True if previous state matched a letter. */
  299.   char backref;            /* True if this state matches a \<digit>. */
  300.   unsigned char constraint;    /* Constraint for this state to accept. */
  301.   int first_end;        /* Token value of the first _END in elems. */
  302. } _dfa_state;
  303.  
  304. /* If an r.e. is at most MUST_MAX characters long, we look for a string which
  305.    must appear in it; whatever's found is dropped into the struct reg. */
  306.  
  307. #define MUST_MAX    50
  308.  
  309. /* A compiled regular expression. */
  310. struct regexp
  311. {
  312.   /* Stuff built by the scanner. */
  313.   _charset *charsets;        /* Array of character sets for _SET tokens. */
  314.   int cindex;            /* Index for adding new charsets. */
  315.   int calloc;            /* Number of charsets currently allocated. */
  316.  
  317.   /* Stuff built by the parser. */
  318.   _token *tokens;        /* Postfix parse array. */
  319.   int tindex;            /* Index for adding new tokens. */
  320.   int talloc;            /* Number of tokens currently allocated. */
  321.   int depth;            /* Depth required of an evaluation stack
  322.                    used for depth-first traversal of the
  323.                    parse tree. */
  324.   int nleaves;            /* Number of leaves on the parse tree. */
  325.   int nregexps;            /* Count of parallel regexps being built
  326.                    with regparse(). */
  327.  
  328.   /* Stuff owned by the state builder. */
  329.   _dfa_state *states;        /* States of the regexp. */
  330.   int sindex;            /* Index for adding new states. */
  331.   int salloc;            /* Number of states currently allocated. */
  332.  
  333.   /* Stuff built by the structure analyzer. */
  334.   _position_set *follows;    /* Array of follow sets, indexed by position
  335.                    index.  The follow of a position is the set
  336.                    of positions containing characters that
  337.                    could conceivably follow a character
  338.                    matching the given position in a string
  339.                    matching the regexp.  Allocated to the
  340.                    maximum possible position index. */
  341.   int searchflag;        /* True if we are supposed to build a searching
  342.                    as opposed to an exact matcher.  A searching
  343.                    matcher finds the first and shortest string
  344.                    matching a regexp anywhere in the buffer,
  345.                    whereas an exact matcher finds the longest
  346.                    string matching, but anchored to the
  347.                    beginning of the buffer. */
  348.  
  349.   /* Stuff owned by the executor. */
  350.   int tralloc;            /* Number of transition tables that have
  351.                    slots so far. */
  352.   int trcount;            /* Number of transition tables that have
  353.                    actually been built. */
  354.   int **trans;            /* Transition tables for states that can
  355.                    never accept.  If the transitions for a
  356.                    state have not yet been computed, or the
  357.                    state could possibly accept, its entry in
  358.                    this table is NULL. */
  359.   int **realtrans;        /* Trans always points to realtrans + 1; this
  360.                    is so trans[-1] can contain NULL. */
  361.   int **fails;            /* Transition tables after failing to accept
  362.                    on a state that potentially could do so. */
  363.   int *success;            /* Table of acceptance conditions used in
  364.                    regexecute and computed in build_state. */
  365.   int *newlines;        /* Transitions on newlines.  The entry for a
  366.                    newline in any transition table is always
  367.                    -1 so we can count lines without wasting
  368.                    too many cycles.  The transition for a
  369.                    newline is stored separately and handled
  370.                    as a special case.  Newline is also used
  371.                    as a sentinel at the end of the buffer. */
  372.   char must[MUST_MAX];
  373.   int mustn;
  374. };
  375.  
  376. /* Some macros for user access to regexp internals. */
  377.  
  378. /* ACCEPTING returns true if s could possibly be an accepting state of r. */
  379. #define ACCEPTING(s, r) ((r).states[s].constraint)
  380.  
  381. /* ACCEPTS_IN_CONTEXT returns true if the given state accepts in the
  382.    specified context. */
  383. #define ACCEPTS_IN_CONTEXT(prevn, currn, prevl, currl, state, reg) \
  384.   _SUCCEEDS_IN_CONTEXT((reg).states[state].constraint,           \
  385.                prevn, currn, prevl, currl)
  386.  
  387. /* FIRST_MATCHING_REGEXP returns the index number of the first of parallel
  388.    regexps that a given state could accept.  Parallel regexps are numbered
  389.    starting at 1. */
  390. #define FIRST_MATCHING_REGEXP(state, reg) (-(reg).states[state].first_end)
  391.  
  392. /* Entry points. */
  393.  
  394. #if __STDC__
  395.  
  396. /* Regsyntax() takes two arguments; the first sets the syntax bits described
  397.    earlier in this file, and the second sets the case-folding flag. */
  398. extern void regsyntax(int, int);
  399.  
  400. /* Compile the given string of the given length into the given struct regexp.
  401.    Final argument is a flag specifying whether to build a searching or an
  402.    exact matcher. */
  403. extern void regcompile(const char *, size_t, struct regexp *, int);
  404.  
  405. /* Execute the given struct regexp on the buffer of characters.  The
  406.    first char * points to the beginning, and the second points to the
  407.    first character after the end of the buffer, which must be a writable
  408.    place so a sentinel end-of-buffer marker can be stored there.  The
  409.    second-to-last argument is a flag telling whether to allow newlines to
  410.    be part of a string matching the regexp.  The next-to-last argument,
  411.    if non-NULL, points to a place to increment every time we see a
  412.    newline.  The final argument, if non-NULL, points to a flag that will
  413.    be set if further examination by a backtracking matcher is needed in
  414.    order to verify backreferencing; otherwise the flag will be cleared.
  415.    Returns NULL if no match is found, or a pointer to the first
  416.    character after the first & shortest matching string in the buffer. */
  417. extern char *regexecute(struct regexp *, char *, char *, int, int *, int *);
  418.  
  419. /* Free the storage held by the components of a struct regexp. */
  420. extern void regfree(struct regexp *);
  421.  
  422. /* Entry points for people who know what they're doing. */
  423.  
  424. /* Initialize the components of a struct regexp. */
  425. extern void reginit(struct regexp *);
  426.  
  427. /* Incrementally parse a string of given length into a struct regexp. */
  428. extern void regparse(const char *, size_t, struct regexp *);
  429.  
  430. /* Analyze a parsed regexp; second argument tells whether to build a searching
  431.    or an exact matcher. */
  432. extern void reganalyze(struct regexp *, int);
  433.  
  434. /* Compute, for each possible character, the transitions out of a given
  435.    state, storing them in an array of integers. */
  436. extern void regstate(int, struct regexp *, int []);
  437.  
  438. /* Error handling. */
  439.  
  440. /* Regerror() is called by the regexp routines whenever an error occurs.  It
  441.    takes a single argument, a NUL-terminated string describing the error.
  442.    The default regerror() prints the error message to stderr and exits.
  443.    The user can provide a different regfree() if so desired. */
  444. extern void regerror(const char *);
  445.  
  446. #else /* ! __STDC__ */
  447. extern void regsyntax(), regcompile(), regfree(), reginit(), regparse();
  448. extern void reganalyze(), regstate(), regerror();
  449. extern char *regexecute();
  450. #endif /* ! __STDC__ */
  451.